<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\userapply;
use App\Models\User;
class UserapplyController extends Controller
{
    protected $name = '用户审批';
    protected $find = ['id', 'name', 'tel', 'applytype', 'state', 'des', 'operator', 'created_at', 'approvedate'];
    //
    /**
     * 查询
     */
    public function find(Request $request)
    {
        try {
            $param = json_decode($request->param, true);

            $operator = $this->I($param['operator'] ?? null);
            $datebegin = $this->I($param['datebegin'] ?? null);
            $dateend = $this->I($param['dateend'] ?? null);
            $applytype = $this->I($param['applytype'] ?? null);
            $type = $this->I($param['type'] ?? null);
            $page = intval($this->I($param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 50));
            $where = ' a.isdel=0 ';

            if (!empty($operator)) {
                $where .= " and a.name = '$operator' ";
            }
            if (!empty($datebegin)) {
                $where .= " and a.created_at >= '$datebegin' ";
            }
            if (!empty($dateend)) {
                $where .= " and a.created_at < '$dateend 23:59:59' ";
            }
            if (!empty($applytype)) {
                $where .= " and a.applytype = '$applytype' ";
            }
            // 0:待审批 1:已审批 -1:已驳回
            if (!empty($type)) {
                if ($type == '待审批') {
                    $where .= " and a.state = 0 ";
                } else if ($type == '驳回') {
                    $where .= " and a.state = -1 ";
                } else if ($type == '已审批') {
                    $where .= " and a.state = 1 ";
                }
            }
            $temp = DB::table('userapply as a')
                ->select($this->find)
                ->whereRaw($where)
                ->orderBy('a.created_at', 'desc')
                ->paginate($pagecount, ['id'], 'page', $page)
                ->toArray(); // 控制页码，默认每页 10 条
            $res = $temp['data'];
            $allcount = $temp['total'];
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }
    /**
     * 审批处理
     */
    public function handle(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $des = $this->I($param['des'] ?? null);
            $type = $this->I($param['type'] ?? null);
            $applytype = $this->I($param['applytype'] ?? null);
            $applydata = userapply::where('id', $id)->first();

            if ($type == true) {
                $Handletype = '审批';
            } else if ($type == false) {
                $Handletype = '驳回';
            } else {
                return $this->ajaxReturn(['code' => 0, 'msg' => '操作失败:审核参数错误!']);
            }
            if (empty($applydata)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '操作失败:申请不存在!']);
            }
            $res = false;
            if ($applytype == '用户注册') {
                if ($type) {
                    $res = $this->UsrRegister($param, $applydata);
                } else {
                    $res = true;
                }
            }
            //记录日志
            $this->log(['type' => '审批', 'billcaption' => '用户审批', 'des' => '操作人[' . $Handletype . ']了用户[' . $applydata->name . ']的申请,申请类型为[' . $applytype . ']']);
            if (is_bool($res) && $res == true) {
                $usr = $this->decodetoken();
                userapply::where('id', $id)->update(['state' => $type ? 1 : -1, 'des' => $des, 'operator' => $usr->name, 'approvedate' => date('Y-m-d H:i:s')]);
                return $this->ajaxReturn(['code' => 1, 'msg' => $Handletype . '成功']);
            } else {
                return $this->ajaxReturn(['code' => 0, 'msg' => $Handletype . '失败', 'data' => $res]);
            }
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '审批失败：' . $e->getMessage()]);
        }
    }

    private function UsrRegister($param, $applydata)
    {
        try {
            $id = $this->I($param['id'] ?? null);
            $channelid = $this->I($param['channelid'] ?? null);
            $isadmin = $this->I($param['isadmin'] ?? null);
            $iscreateemp = $this->I($param['iscreateemp'] ?? null);
            $deptid = $this->I($param['deptid'] ?? null);
            $employeeid = $this->I($param['employeeid'] ?? null);
            $name = $applydata->name;
            $tel = $applydata->tel;
            $data = json_decode($applydata->data, true);
            $password = $data['password'];
            $roleid = null;

            //获取用户最大编号
            $FSQL = " SELECT MAX(CAST(CASE WHEN userid REGEXP '^[0-9]+$' THEN userid ELSE NULL END AS SIGNED)) AS userid FROM users;";
            $userid = intval(DB::select($FSQL)[0]->userid);
            if ($userid == 0) {
                $userid = '000001';
            } else {
                $userid++;
                $userid = str_pad($userid, 6, '0', STR_PAD_LEFT);
            }

            if ($isadmin) {
                $FSQL = "SELECT a.id,a.name,a.usrgroupid
                    FROM UsrGroup a where name ='系统管理员'";
                $data = DB::select($FSQL);
                $roleid = $data[0]->id;
            }
            $emplsit = [];
            if ($iscreateemp) {
                $FSQL = " select id,userid,employeeid from Employee where name='$name' and isdel=0";
                $tempdata = DB::select($FSQL);
                if (!empty($tempdata) && empty($tempdata[0]->userid)) {
                    //如果人事档案有存在的人名,并且没有绑定用户，则使用它
                    $employeeid = $tempdata[0]->employeeid;
                    DB::table('userrole')->where('id', $tempdata[0]->id)->update(['userid' => $userid]);
                } else {
                    //如果没有，则创建一个新的记录
                    //默认工号是电话
                    $employeeid = $tel;
                    $emplsit = [
                        'userid' => $userid,
                        'name' => $name,
                        'employeeid' => $employeeid,
                        'deptid' => $deptid,
                        'tel' => $tel,
                        'state' => '在职',
                        'browsepswd' => $password
                    ];
                }
            }
            $usrlist = [
                'userid' => $userid,
                'name' => $name,
                'tel' => $tel,
                'password' => $password,
                'employeeid' => $employeeid,
                'channelid' => $channelid
            ];
            $user = User::create($usrlist);
            if (!empty($emplsit)) {
                DB::table('Employee')->insert($emplsit);
            }
            if ($roleid) {
                $rolelist = [];
                $rolelist['userid'] = $user->id;
                $rolelist['roleid'] = $roleid;
                $rolelist['isdel'] = 0;
                DB::table('userrole')->insert($rolelist);
            }
            return true;
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '注册创建用户失败!','error'=>$e->getMessage()]);
        }
    }

}
